<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card class="box-card">
      <el-button type="primary" class="addRolesBtn" @click="addVisible = true"
        >添加角色</el-button
      >
    </el-card>
    <!-- 角色列表区域 -->
    <el-table :data="RolesList" style="width: 100%" stripe border>
      <!-- 展开列表详细信息 -->
      <el-table-column type="expand">
        <template slot-scope="props">
          <!-- 栅格布局-->
          <el-row
            v-for="(item1, index1) in props.row.children"
            :key="item1.id"
            :class="['bdbottom', index1 === 0 ? 'bdtop' : '', 'vcenter']"
          >
            <!-- 一级权限  -->
            <el-col :span="5">
              <el-tag closable @close="removeRightById(props.row, item1.id)">{{
                item1.authName
              }}</el-tag>
              <i class="el-icon-caret-right"></i>
            </el-col>
            <!-- 渲染二级和三级权限 -->
            <el-col :span="19">
              <!-- 通过for循环嵌套二级权限 -->
              <el-row
                v-for="(item2, index2) in item1.children"
                :key="item2.id"
                :class="[index2 === 0 ? '' : 'bdtop', 'vcenter']"
              >
                <!-- 二级 -->
                <el-col :span="6"
                  ><el-tag
                    type="success"
                    closable
                    @close="removeRightById(props.row, item2.id)"
                    >{{ item2.authName }}</el-tag
                  ><i class="el-icon-caret-right"></i
                ></el-col>
                <!-- 三级 -->
                <el-col :span="18">
                  <el-tag
                    v-for="item3 in item2.children"
                    :key="item3.id"
                    type="warning"
                    closable
                    @close="removeRightById(props.row, item3.id)"
                    >{{ item3.authName }}</el-tag
                  >
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <!-- 索引列 -->
      <el-table-column type="index" label="#" align="center"></el-table-column>
      <el-table-column
        prop="roleName"
        label="角色名称"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="roleDesc"
        label="角色描述"
        align="center"
      ></el-table-column>
      <el-table-column label="操作" width="300px">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-edit"
            @click="showEditDialog(scope.row.id)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="danger"
            icon="el-icon-delete"
            @click="removeRoleById(scope.row.id)"
            >删除</el-button
          >
          <el-button
            size="mini"
            type="warning"
            icon="el-icon-setting"
            @click="showSetRightDialog(scope.row)"
            >分配权限</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 添加角色对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addVisible"
      width="50%"
      @close="addRolesClosed"
    >
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input
            v-model="addForm.roleName"
            placeholder="角色名称必填项"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 编辑角色对话框 -->
    <el-dialog
      title="编辑角色"
      :visible.sync="editVisible"
      width="50%"
      @close="editRolesClosed"
    >
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoles">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 显示分配权限的对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="SetRightVisible"
      width="30%"
      @close="resetTree"
    >
      <!-- 树形组件 @default-expand-all 默认展开所有节点 -->
      <el-tree
        :data="RightsList"
        :props="treeProps"
        node-key="id"
        show-checkbox
        default-expand-all
        :default-checked-keys="defkeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="SetRightVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Roules',
  data() {
    return {
      RolesList: [],
      addVisible: false,
      editVisible: false,
      SetRightVisible: false,
      RightsList: [],
      defkeys: [], // 默认选中的节点ID数组
      roleId: '', // 当前即将分配权限的角色Id
      addForm: {
        roleName: '',
        roleDesc: ''
      },
      editForm: {},
      // 角色名称不能为空 增加角色验证
      addFormRules: {
        roleName: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ]
      },
      // 验证编辑角色不能为空
      editFormRules: {
        roleName: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ]
      },
      // 树形框展示标题
      treeProps: {
        children: 'children',
        label: 'authName'
      }
    }
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        this.$message.error('获取权限列表失败')
      }
      // console.log(res.data)
      this.RolesList = res.data
    },
    // 删除标签 根据id删除对应的权限
    async removeRightById(role, rightId) {
      // 弹窗用户是否确定删除
      const confirmResult = await this.$confirm('是否确定删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消了删除')
      }
      // 发起请求删除指定角色的指定权限 roleId角色id rightId 权限id
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除权限失败')
      }
      this.$message.success('删除权限成功')
      // this.getRolesList() // 会让页面合拢不建议 因为删除后服务器返回最新的权限重新赋值即可
      role.children = res.data
    },
    // 添加角色
    addRoles() {
      // 提交预验证
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        // 发起网络请求
        const { data: res } = await this.$http.post('roles', this.addForm)
        if (res.meta.status !== 201) {
          return this.$message.error('添加角色失败')
        }
        this.$message.success('添加角色成功')
        // 关闭对话框 并刷新列表
        this.addVisible = false
        this.getRolesList()
      })
    },
    // 编辑角色
    editRoles() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        // 发起网络请求修改
        const { data: res } = await this.$http.put(`roles/${this.editForm.roleId}`, { roleName: this.editForm.roleName, roleDesc: this.editForm.roleDesc })
        if (res.meta.status !== 200) {
          return this.$message.error('修改失败')
        }
        this.$message.success('修改成功')
        this.editVisible = false
        this.getRolesList()
      })
    },
    // 重置表单
    addRolesClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 监听编辑角色对话框
    editRolesClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 展示编辑角色对话框数据
    async showEditDialog(id) {
      // 根据id查询角色
      const { data: res } = await this.$http.get(`roles/${id}`)
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色信息失败')
      }
      this.editForm = res.data
      this.editVisible = true
    },
    // 删除角色
    async removeRoleById(id) {
      const confirmResult = await this.$confirm('此操作将永久删除该用户角色权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
      // 如果用户确认删除 则返回值为字符串confirm
      // 如果用户取消删除 则返回值为字符串cancel
      if (confirmResult === 'confirm') {
        const { data: res } = await this.$http.delete(`roles/${id}`)
        if (res.meta.status !== 200) {
          return this.$message.error('删除用户角色失败')
        }
        this.$message.success('删除用户成功')
        this.getRolesList()
      }
    },
    // 显示分配权限的对话框
    async showSetRightDialog(role) {
      this.roleId = role.id
      // 获取所有权限数据
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取数据失败')
      }
      // console.log(role)
      this.RightsList = res.data
      // 获取三级节点的id
      this.getDefkeys(role, this.defkeys)
      this.SetRightVisible = true
    },
    // 关闭树形对话框 重置defkey数组
    resetTree() {
      this.defkeys = []
    },
    // 通过递归的方式 获取角色所有三级权限的id 并保存到defkeys数组中
    getDefkeys(node, arr) {
      // 如果没有children 则证明是三级权限没有下集
      if (!node.children) {
        // console.log(arr)
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getDefkeys(item, arr)
      })
    },
    // 分配权限提交按钮 getCheckedKeys被选中节点key的数组 getHalfCheckedKeys半选中节点key的数组
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idsStr = keys.join(',')
      // 发送请求
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idsStr })
      if (res.meta.status !== 200) {
        return this.$message.error('修改失败')
      }
      this.$message.success('修改成功')
      this.getRolesList()
      this.SetRightVisible = false
    }
  },
  created() {
    // 获取角色列表
    this.getRolesList()
  }
}
</script>

<style lang="less" scoped>
.box-card {
  text-align: left;
}
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
